import CryptoJS from "crypto-js";

type StoreType = "localStorage" | "sessionStorage";

interface IStoreTactic {
  setItem(key: string, data: any): void;
  getItem<T = any>(key: string): T | null;
  removeItem(key: string): void;
}

class StoreTactic {
  private storage: Storage;

  constructor(public type: StoreType = "sessionStorage") {
    this.storage = type === "localStorage" ? localStorage : sessionStorage;
  }

  setItem(key: string, data: any): void {
    const ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), import.meta.env.VITE_SecretKey).toString();
    this.storage.setItem(key, ciphertext);
  }

  getItem<T = any>(key: string): T | null {
    const ciphertext = this.storage.getItem(key);
    if (ciphertext) {
      try {
        const bytes = CryptoJS.AES.decrypt(ciphertext, import.meta.env.VITE_SecretKey);
        const decryptedData = bytes.toString(CryptoJS.enc.Utf8);
        return JSON.parse(decryptedData) as T;
      } catch (error) {
        console.error("解密失败:", error);
        return null;
      }
    }
    return null;
  }

  removeItem(key: string): void {
    this.storage.removeItem(key);
  }

  clear(): void {
    this.storage.clear();
  }
}

export const StoreMap: Record<StoreType, IStoreTactic> = {
  localStorage: new StoreTactic("localStorage"),
  sessionStorage: new StoreTactic("sessionStorage"),
};
